package com.tian.util;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

/**
 * @author tianwc  公众号：java后端技术全栈、面试专栏
 * @version 1.0.0
 * 2023年11月21日 09:41
 * 在线刷题 1200+题和1000+篇干货文章：<a href="https://woaijava.cc/">博客地址</a>
 */
public class XmlUtil {
    private static final String PREFIX_XML = "<xml>";
    private static final String SUFFIX_XML = "</xml>";

    private static final String PREFIX_CDATA = "<![CDATA[";

    private static final String SUFFIX_CDATA = "]]>";

    /**
     * 转化成xml, 单层无嵌套
     *
     * @param paramMap
     * @param isAddCData
     * @return
     */
    public static String mapToXml(Map<Object, Object> paramMap, boolean isAddCData) {
        StringBuilder stringBuilder = new StringBuilder(PREFIX_XML);
        if (null != paramMap) {
            for (Entry<Object, Object> entry : paramMap.entrySet()) {
                stringBuilder.append("<").append(entry.getKey()).append(">");
                if (isAddCData) {
                    stringBuilder.append(PREFIX_CDATA);
                    if (null != entry.getValue()) {
                        stringBuilder.append(entry.getValue());
                    }
                    stringBuilder.append(SUFFIX_CDATA);
                } else {
                    if (null != entry.getValue()) {
                        stringBuilder.append(entry.getValue());
                    }
                }
                stringBuilder.append("</").append(entry.getKey()).append(">");
            }
        }
        return stringBuilder.append(SUFFIX_XML).toString();
    }


    /**
     *   将xml字符串转换成map
     */
    public static Map<String, String> xml2Map(String xml) {
        Map<String, String> map = new HashMap<String, String>();
        Document doc = null;
        try {
            // 将字符串转为XML
            doc = DocumentHelper.parseText(xml);
            // 获取根节点
            Element rootElt = doc.getRootElement();
            @SuppressWarnings("unchecked")
            // 获取根节点下所有节点
            List<Element> list = rootElt.elements();
            // 遍历节点
            for (Element element : list) {
                // 节点的name为map的key，text为map的value
                map.put(element.getName(), element.getText());
            }
        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return map;
    }
}